package com.wkq.util

import android.webkit.JavascriptInterface
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient

/**
 * 通用 WebView HTML 工具类，支持 HTML 渲染、图片点击回调、透明字体色
 */
class HtmlWebViewHelper(
    private val webView: WebView
) {

    /** 样式配置 **/
    var styleConfig = StyleConfig()

    /** 图片点击监听 **/
    var imageClickListener: ((src: String, pos: Int, allUrls: List<String>) -> Unit)? = null

    /** 加载HTML **/
    fun load(content: String, fontSize: Int = 14) {
        val html = buildHtml(content, fontSize)
        configureWebView()
        webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null)
    }

    /** 清理资源 **/
    fun clear() {
        webView.removeJavascriptInterface("ImageHandler")
        imageClickListener = null
    }

    /** 构造HTML **/
    private fun buildHtml(content: String, fontSize: Int): String {
        val cssTextColor = parseColor(styleConfig.textColor)
        return """
            <html>
                <head>
                    <meta charset="UTF-8">
                    <style>
                        body {
                            padding: ${styleConfig.padding};
                            margin: ${styleConfig.margin};
                            font-size: ${fontSize}px;
                            color: $cssTextColor;
                            background: transparent;
                            line-height: ${styleConfig.lineHeight};
                        }
                        img {
                            width: 100%;
                            height: auto;
                            margin: ${styleConfig.imageMargin};
                        }
                    </style>
                </head>
                <body>$content</body>
            </html>
        """.trimIndent()
    }

    /** 配置WebView **/
    private fun configureWebView() {
        webView.settings.apply {
            javaScriptEnabled = true
            loadWithOverviewMode = false
            useWideViewPort = false
            defaultTextEncodingName = "UTF-8"
        }

        webView.addJavascriptInterface(ImageJsInterface(), "ImageHandler")

        webView.webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView, url: String?) {
                injectImageClickJs()
            }
        }
    }

    /** 注入图片点击JS **/
    private fun injectImageClickJs() {
        val js = """
            javascript:(function(){
                var images = document.getElementsByTagName('img');
                var urls = [];
                for (var i = 0; i < images.length; i++) {
                    urls[i] = images[i].src;
                    images[i].setAttribute('data-pos', i);
                    images[i].onclick = function() {
                        window.ImageHandler.onImageClick(this.src, this.getAttribute('data-pos'));
                    }
                }
                window.ImageHandler.onImageUrlsCollected(urls);
            })()
        """.trimIndent()
        webView.loadUrl(js)
    }

    /** JS接口 **/
    private inner class ImageJsInterface {
        private var imageUrls: List<String> = emptyList()

        @JavascriptInterface
        fun onImageUrlsCollected(urls: Array<String>) {
            imageUrls = urls.toList()
        }

        @JavascriptInterface
        fun onImageClick(src: String, pos: String) {
            imageClickListener?.invoke(src, pos.toInt(), imageUrls)
        }
    }

    /** 样式配置 **/
    data class StyleConfig(
        var padding: String = "0px",
        var margin: String = "0px",
        var textColor: String = "#000000",  // 支持 #RRGGBB 或 #AARRGGBB
        var imageMargin: String = "0px",
        var lineHeight: String = "1.5"
    )

    /** 自动解析颜色 **/
    private fun parseColor(hex: String): String {
        val color = hex.removePrefix("#")
        return when (color.length) {
            6 -> { // #RRGGBB
                val r = color.substring(0, 2).toInt(16)
                val g = color.substring(2, 4).toInt(16)
                val b = color.substring(4, 6).toInt(16)
                "rgb($r, $g, $b)"
            }
            8 -> { // #AARRGGBB
                val a = color.substring(0, 2).toInt(16) / 255.0
                val r = color.substring(2, 4).toInt(16)
                val g = color.substring(4, 6).toInt(16)
                val b = color.substring(6, 8).toInt(16)
                "rgba($r, $g, $b, %.2f)".format(a)
            }
            else -> throw IllegalArgumentException("颜色格式错误: $hex")
        }
    }
}
